<template>
    <div class="participant wrap-table user-health" v-loading="loading">
        <div class="headerTop_ukl">
            <ul class="clearfix">
                <li>
                    <p class="p1"><img src="../../assets/images/icon_yanjiuduixiang.png" alt=""/><span>研究对象</span></p>
                    <p class="p3">{{userBasic.Surname}}({{userBasic.ResearchNo}})</p>
                </li>
                <li>
                    <p class="p1"><img src="../../assets/images/icon_ganyuzu.png" alt=""/>{{userBasic.GroupType |GroupType}}</p>
                    <p  class="p3" v-if="userBasic.Period!='3'"><span v-if="userBasic.GroupType==1">{{userBasic.IntensityOfIntervention |IntensityOfIntervention}}</span></p>
                    <p  class="p3" v-else><span v-if="userBasic.GroupType==1">{{userBasic.ChildIntensityOfIntervention |IntensityOfIntervention}}</span></p>
                </li>
                <li >
                    <p class="p1"><img src="../../assets/images/icon_huaiyunqi.png" alt=""/>{{userBasic.Period |Period}}</p>
                    <p  class="p3"><span v-if="userBasic.Period==2">预产期：{{userBasic.ExpectedDate}},{{userBasic.PregnancyWeek}}</span></p>
                    <p class="p3"><span v-if="userBasic.Period==3">出生日期：{{userBasic.ChildBirthDate}},{{userBasic.ChildAge}}, {{userBasic.ChildSex|ChildSex}} </span></p>
                    <p class="p3"><span v-if="userBasic.Period==4">出生日期：{{userBasic.ChildBirthDate}},{{getChildAge2(userBasic.ChildBirthDate)}}, {{userBasic.ChildSex|ChildSex}} </span></p>
                </li>
            </ul>
        </div>
        <div class="bmi-class">
            <p class="clearfix" v-if="userBasic.GroupType==1"><span v-if="userBasic.Period=='1'" style="color: #A6A6A6">研究对象BMI=<span class="bmi-span" :class="{isRed:(womanBmi1>=24 ||womanBmi1<18.5)}">{{womanBmi1}}</span></span><span v-else style="color: #A6A6A6">研究对象孕前BMI= <span class="bmi-span" :class="{isRed:(womanBmi2>=24 ||womanBmi2<18.5)}">{{womanBmi2}}</span></span>
                <span style="color: #A6A6A6;margin-left: 30px;">研究对象丈夫BMI=<span  class="bmi-span" :class="{isRed:(manBmi>=28)}">
                    {{manBmi}}</span></span><span class="watch-span" @click="watchWeight">查看></span>
                <!--<span v-if="userBasic.Period==3" style="color: #A6A6A6;margin-left: 30px;">出生孕周={{birthWeek}}周+{{birthDay}}天</span>-->
                <span v-if="userBasic.Period==3" style="color: #A6A6A6;margin-left: 30px;">出生体重=<span
                        class="bmi-span">{{userBasic
                                                                                           .BirthWeight}}g</span></span>
            </p>
            <el-select v-model="value" placeholder="请选择" style="width: 200px;float: right;margin-top: -35px;"
                       @change="changeSelect">
                <el-option
                        v-for="item in options1"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            </p>
        </div>
        <div class="content" v-if="userBasic.GroupType==1" style="border:1px solid #EDF1F7;padding:15px 0 20px 0;">
            <p class="p1">当研究对象具有以下健康现状时，请勾选</p>
            <template>
                <el-table
                        :data="items"
                        border
                        style="width: 100%;">
                    <el-table-column align="left" header-align="center" label="健康因素" min-width="400"  :show-overflow-tooltip="true">
                        <template  slot-scope="scope">
                            <el-checkbox  :disabled="scope.row.disabled" v-model="scope.row.IsSelected==1" @change="changeCheckBox(scope.row,scope.$index)">{{scope.row.ItemName}}</el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="ConfirmDate"
                            align="center"
                            label="确认时间"
                            min-width="80">
                    </el-table-column>
                    <el-table-column
                            prop="Oparator"
                            label="操作人员"
                            :show-overflow-tooltip="true"
                            align="center"
                            min-width="80">
                    </el-table-column>
                </el-table>
            </template>
            
            <p class="p_date"><span>更新日期</span>
                <el-date-picker
                        style="width: 300px;"
                        v-model="UpdateDate"
                        :clearable="false"
                        type="date"
                        :picker-options="pickerOptions1"
                        placeholder="选择日期">
                </el-date-picker></p>
            <div v-if="value == userBasic.Period"  style="text-align: left;padding-top: 25px;padding-left: 45%" >
                <el-button type="primary" class="pd-bt" @click="saveSure">保存</el-button>
            </div>
            <p style="color:#f00;margin:30px 0px;">{{weightSpan}}</p>
        </div>
        <div v-else-if="userBasic.GroupType==2">
            <i class="el-icon-warning" style="color:#409EFF;margin-top: 20px">不需要为B组研究对象做健康现况评估</i>
        </div>
        <!--健康状况pre-->
        <el-dialog title="研究对象健康状况" :visible.sync="dialogForm" :append-to-body="true" top="0" width="50%" class="user-health"
                   :close-on-click-modal="false">
            <div>
                <div>
                    <div class="contents">
                        <p class="p2 ">您输入了以下健康信息，请再次核对：</p>
                        <ul style="margin-top: 30px;">
                            <li v-for="lab in ckeckLabels">
                                <i class="el-icon-info"></i>{{lab}}
                            </li>
                        </ul>
                        <h3 class="p2 " v-if="ckeckLabels.length<=0">未勾选任何危险因素</h3>
                    </div>
                    <p style="margin:10px;color:#f00">修改健康现况将导致研究对象干预强度从A转为AA，并重置其日程待办事项，请谨慎操作。<br/>若以上信息核对无误，请点击【确认】，若信息有误，请点击【取消】并及时更正。</p>
                    <div slot="footer" class="dialog-footer">
                        <span>
                            <el-button @click="dialogForm = false">取 消</el-button>
                            <el-button type="primary" :disabled="onSaveoff" @click="saveHealth">确认</el-button>
                        </span>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {DIC_PERIODB,filterPeriod,filterIntensityOfIntervention} from '@/utils/localDic'
import {getChildAge2} from '@/utils/index'
export default {
    data() {
        return {
            trueRadio:true,
            weightSpan:"",
            checkeditems:[],
            items:[],
            itemType:'',
            sysId:'',
            mobile:'',
            trueRadio:true,
            researchNo:'',
            userBasic:{
                Surname:'',
                ResearchNo:'',
                ExpectedDate:'',
                Period:'',
                IntensityOfIntervention:'',
                GroupType:''
            },
            items:[],
            checkeditems:[],
            ckeckIds:[],
            ckeckLabels:[],
            bmiData:'',
            loading:true,
            isRed:'isRed',
            isDanger:true,
            dialogForm:false,
            oldItems:[],  //对照组
            UpdateDate:'',
            pickerOptions1:{
                disabledDate(time) {
                    let nowDate=dateForm(new Date())
                    return dateForm(time) !== nowDate
                },
            },
            onSaveoff:false,
            options1: DIC_PERIODB,
            value:'',
            Periodcell:'',
            isCheck:false,
        }
    },
    props:{
        changeIndex:{
            type: String,
        }
    },
    watch:{
        changeIndex:{
            handler:function(index){
                if(index=='1'){
                    this.getList()
                }    
            },
            //immediate:true

        }
    },
    components:{

    },
    computed:{
        ...mapGetters([
                'resechObj',
                'userIcon',
                'token',
                'UserDic'
            ]),
        womanBmi1:function () {
            return computedBIM(this.bmiData.Weight, this.bmiData.Height)
        },
        womanBmi2:function () {
            return computedBIM(this.bmiData.PreWeight, this.bmiData.Height)
        },
        manBmi:function () {
            return computedBIM(this.bmiData.HusbandWeight, this.bmiData.HusbandHeight)
        },
        LASTTIME:function(){
            let dateAlary=new Date(this.userBasic.ExpectedDate)
            return new Date(dateForm(dateAlary.setMonth(dateAlary.getMonth()-9,dateAlary.getDate()-7)))
        },
        yunzhou:function(){
            return parseInt((WeeksBetw(new Date,this.LASTTIME))/7)
        },
        yuntianshu:function(){
            return parseInt((WeeksBetw(new Date,this.LASTTIME))%7)
        },
        birthWeek(){
            return parseInt((WeeksBetw(new Date,new Date(this.userBasic.ChildBirthDate)))/7)    
        },
        birthDay(){
            return parseInt((WeeksBetw(new Date,new Date(this.userBasic.ChildBirthDate)))%7)
        }
    },
    created() {
        console.log(this.UserDic)
    },
    methods: {
        getChildAge2(val){ //获取儿童期2年龄
            return val && getChildAge2(val)
        },
        getWeight() {
            if(this.userBasic.Period != '3'){
                return false
            }
            this.service({
                url: "ResearchObject/GetBirthWeightPercentile",
                method: "get",
                params: {
                sex: this.userBasic.ChildSex ,
                birthAge: this.userBasic.BirthWeek,
                },
            }).then((res) => {
                if(res.dtData.length>0){
                if( parseInt(res.dtData[0].P10)> parseInt(this.userBasic.BirthWeight)){
                    this.weightSpan = "出生体重<P10，请在健康现况中勾选“此次分娩诊断小于胎龄儿"
                }
                else if(parseInt(res.dtData[0].P90) < parseInt(this.userBasic.BirthWeight)){
                    this.weightSpan = "出生体重>P90，请在健康现况中勾选“此次分娩诊断大于胎龄儿 "
                }
                }
                console.log(res);
            });
        },
        changeCheckBox:function(row,index){   //checkbox事件   对照两组数据
        console.log(row)
            let that=this;
            if(row.IsSelected=='1'){
                that.$set(that.items[index],'IsSelected','0')
                row.IsSelected_Old=0
            }
            else{
                that.$set(that.items[index],'IsSelected','1')
                row.ItemId=row.HealthConditionItemId
                row.IsSelected_Old=1
            }
            //constrast
            if(that.items[index].IsSelected!=(that.oldItems[index].IsSelected||'0')){
                row.ConfirmDate=dateForm(new Date());
                row.Oparator=that.userIcon;
                row.OparatorId=that.token;
                row.UpdateDate=dateForm(new Date());
            }
            else{
                row.ConfirmDate=that.oldItems[index].ConfirmDate ||'';
                row.Oparator=that.oldItems[index].Oparator||'';
                row.OparatorId=that.oldItems[index].OparatorId||'';
                row.UpdateDate=that.oldItems[index].UpdateDate||'';
            }
            row.ResearchObjectId=that.userBasic.SYS_ID;
        },
        watchWeight:function(){
            this.$emit('watchWeight','5')
        },
        changeSelect:function(val){  //换孕前
            this.Periodcell=val
            this.getList(1)
        },
        getList:function(ischecked,callback){           //获取一级信息列表
            let that=this;
            that.loading=true
            that.checkeditems=[];
            that.userBasic={
                Surname:'',
                ResearchNo:'',
                ExpectedDate:'',
                Period:that.Periodcell,
                IntensityOfIntervention:'',
                GroupType:''
            },
            that.bmiData='';
            that.ckeckIds=[];
            that.ckeckLabels=[];
            if(that.resechObj.mobile ||that.resechObj.researchNo){
                that.sysId='';
                that.mobile=that.resechObj.mobile;
                that.researchNo=that.resechObj.researchNo;
            }
            that.service({
                url:'/ResearchObject/GetParticipantDetail',
                method:'get',
                params:{
                    itemType:'2',
                    sysId:'',
                    period:that.Periodcell,
                    mobile:that.mobile,
                    researchNo:that.researchNo,
                    ResearchObjectId:that.sysId,
                    pageCount:0,
                    pageSize: 100,
                }
            }).then(response=>{

                response.dtData.dtBasic[0]? that.userBasic=response.dtData.dtBasic[0]:'';
                response.dtData.dtHeightAndWeight[0]?that.bmiData=response.dtData.dtHeightAndWeight[0]:'';
                that.items=response.dtData.dtHCondition;
                console.log(that.userBasic)
                that.oldItems=JSON.parse(JSON.stringify(response.dtData.dtHCondition));
                for(let i of that.items){
                    if(i.IsSelected == '1'){
                        i.disabled = true
                    }
                    if(i.IsSelected_Old=='1' && i.IsSelected==undefined){
                        that.$set(i,'IsSelected','1')
                        that.$set(i,'hasReady','1')
                    }
                }
                that.UpdateDate=response.dtData.dtBasic[0].HealthConditionUpdateDate||''
                that.loading=false
                that.getWeight()
                if(ischecked && ischecked==1) {  //如果是首次加载则直接赋值
                   return false
                }
                that.value = that.userBasic.Period
                callback()
                that.onSaveoff=false;
                
            }).catch(data=>{
                that.onSaveoff=false;
            })
        },
        saveSure:function(){
            let that=this;
            if(that.UpdateDate==''){
                that.$message({
                    message:'请选择更新日期',
                    type:'error'
                })
                return false
            }
            that.dialogForm=true;
            that.ckeckIds=[];
            that.ckeckLabels=[];
            for(let item of that.items){
                if(item.IsSelected==1){
                    that.ckeckLabels.push(item.ItemName)
                    that.ckeckIds.push(item)
                }
            }
            console.log(that.items)
        },
        saveHealth:function(){   //保存
            this.$confirm('是否确认?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                let that=this;
            if(that.onSaveoff){
                return false;
            }
            that.items[0].UpdateDate=dateForm(new Date());
            that.items[0].OparatorId=that.token;
            that.onSaveoff=true
            if(that.ckeckIds.length==0 && that.userBasic.IntensityOfIntervention=='2'){
                that.items=[];
            }
	        that.items=that.items.filter((item)=>{
            	return item.ItemId
            })
            that.service({
                url: "/ResearchObject/SaveHealthConditionTwo",
                method: "post",
                data: {
                    ResearchObjectId:that.userBasic.SYS_ID,
                    ListHealthConditionTwoObj:that.items,
                    IsUpdate:'1',
	                OparatorId:JSON.parse(that.UserDic).SYS_ID,
	                Oparator:that.userIcon,
	                Period:this.userBasic.Period,
                    HealthConditionUpdateDate:dateForm(new Date()),
                    IntensityOfIntervention:(that.ckeckIds.length==0&&that.userBasic.IntensityOfIntervention==2)?'2':'1',
                }}).then(response => {
                    that.$message({
                        type:'success',
                        message:response.msg
                    })
                    that.dialogForm=false;
                    that.UpdateDate=''
                    if(
                    	(that.userBasic.IntensityOfIntervention==1 && that.userBasic.Period!='3' )
                        ||(that.userBasic.IntensityOfIntervention==2 && that.ckeckIds.length==0 && that.userBasic.Period!='3')
                        || (that.userBasic.ChildIntensityOfIntervention==1 && that.userBasic.Period=='3')
                        || (that.userBasic.ChildIntensityOfIntervention==2 &&  that.ckeckIds.length==0 && that.userBasic.Period=='3')
                        || that.userBasic.Period=='4'
                    ){
                        that.getList()
                        that.loading=false
                    }
                     else{
                        that.getList(3, function () {
                            that.loading=true
                                that.service({
                                    url:'/ResearchObject/ChangeSchedule',
                                    method:'post',
                                    data:{
                                        SYS_ID:that.userBasic.SYS_ID
                                    }
                                }).then(response=>{
                                    that.loading=false
                                    that.$alert('已更新研究对象日程！', '提示', { confirmButtonText: '知道了',})
                                }).catch(data=>{
                                that.loading=false
                                })
                        })
                    }
                //
                }).catch(data => {
                    that.dialogForm=false;
                    that.loading=false;
                    that.onSaveoff=false;
            });
            }).catch(() => {
                this.dialogForm=false;
                    this.loading=false;
                    this.onSaveoff=false;
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
            
        }
    },
    mounted:function(){
        let that=this;
        that.sysId=that.$route.query.id;
        that.mobile=that.$route.query.mobile;
        that.researchNo=that.$route.query.researchNo;
        that.getList()
    },
    filters:{
        GroupType:function(val){
            if(val=='' ||val==undefined){
                return ''
            }
            return val=='1'?'A': 'B'
        },
        IntensityOfIntervention:function(val){
            return filterIntensityOfIntervention(val)
        },
        Period:function(val){
            return filterPeriod(val)
        },
        ChildSex(val){
            return val=='1'?'男':val=='2'?'女':'未知'
        }
    }
  }
function computedBIM(w,h){   //计算BMI
    return isNaN(parseFloat(w)/((parseFloat(h)/100)*(parseFloat(h)/100)))?'-':(parseFloat(w)/((parseFloat(h)/100)*(parseFloat(h)/100))).toFixed(1)
}
function addZero(s){
    return s < 10 ? '0' + s: s;
}

function dateForm(data){   //日期格式化
    return   new Date(data).getFullYear()+'-'+addZero((new Date(data).getMonth()+1))+'-'+addZero(new Date(data).getDate())
}
function WeeksBetw(date1,date2) {  //计算日期之间相差得天数
    var _dt1=new Date(date1);
    var _dt2=new Date(date2);
    var dt1=_dt1.getTime();
    var dt2=_dt2.getTime();
    return parseInt(Math.abs(dt1- dt2)/1000/60/60/24);//这里是计算天数,如果想获得周数则在该返回值上再除以7
}
</script>
<style scoped lang="scss">
    .user-health{
        max-width: 100%;
    }
   .headerTop{
       p{
            padding:10px;
           font-size:16px;
            color:#303133;
           span{
               padding:10px;
           }
           .span1{
               margin-left: 25px;
           }
       }
   }
    .content{
        margin:20px;
        p{
            color:#323232;
            position: relative;
            padding-left: 25px;
            .span1{
                position: absolute;
                right: 20px;
                top: 0px;
                color: #323232;
                margin-right: 10px;
            }
            .span2{
                position: absolute;
                right: 20%;
                top: 0px;
                color: #323232;
                margin-right: -10px;
            }

        }
        .p1{
            padding-bottom:10px;
        }
    }
.headerTop_ukl{
    /*border:1px solid #EDF1F7;*/
    padding:5px 20px 10px 20px;
    min-width: 800px;
    width:1000px;
    font-size:14px;
    ul{
        li{
            float: left;
            margin-right: 50px;
            .p1{
                color:#999999;
                padding-bottom:5px;
                display: inline-block;
                img{
                    display: inline-block;margin-right: 10px;
                };

            }
            .p3{
                display: inline-block;
                padding-left: 10px;
                color: #666;
            }
        }
    }
}
    .bmi-class{
        margin:10px 20px;
        font-size:14px;
        .bmi-span{
            color: #666;
            font-size: 16px;
            padding-left: 5px;
            font-weight:bolder;
        }
        .watch-span{
            color:#279EFB;
            cursor: pointer;
            margin-left: 20px;
        }
    }
    .isRed{color: red !important;}
    .contents{
        margin:0px;
    .p1{
        color:#ccc;
        text-align: center;
        font-size: 15px;
        margin-top: 10px;
    }

    .p2{
        text-align: center;
        margin-top: 5px;
    i{
        cursor: pointer;
        padding:0 10px;
    }
    }
    ul{
    li{
        margin:10px;
        font-size:16px;
        line-height:1.5;
    i{
        color: #409EFF;
        padding-right: 10px;
    }
    }
    }
    }
    .p_date{
        padding:20px;
        span{
            padding-right: 20px;
        }
    }
</style>
